package com.falko.android.raven;

//import java.util.Random;

import android.content.Context;
import android.content.SharedPreferences;
import android.service.wallpaper.WallpaperService;
import android.view.MotionEvent;
import android.view.SurfaceHolder;

import com.falko.android.raven.animator.Animation;
import com.falko.android.raven.animator.AnimationFactory;
import com.falko.android.raven.animator.AnimationFactory.AnimationType;
import com.falko.android.raven.renderer.AnimationRenderer;
import com.falko.android.raven.renderer.GLSurfaceView;
import com.falko.android.raven.util.AutoSpawnThread;

public class RavenWallpaperService extends WallpaperService {

	public static final String SHARED_PREFS_NAME = "ravenSettings";

	@Override
	public Engine onCreateEngine() {

		return new RavenWallpaperEngine(getApplicationContext(),
				getSharedPreferences(SHARED_PREFS_NAME, 0));
	}

	public class RavenWallpaperEngine extends Engine implements
			SharedPreferences.OnSharedPreferenceChangeListener {

		private boolean visible_ = true;
		private GLSurfaceView display_ = null;
		private AnimationRenderer renderer_ = null;
		private AnimationFactory animationFactory_ = null;
		private AutoSpawnThread autoThread_ = null;

		// user preferences
		private volatile boolean autoThreadPaused_ = true;
		private volatile boolean touchEnabled_ = true;

		public RavenWallpaperEngine(Context c, SharedPreferences prefs) {

			animationFactory_ = new AnimationFactory();
			display_ = new GLSurfaceView(getSurfaceHolder());
			renderer_ = new AnimationRenderer(c,
					animationFactory_.getTextureLibrary(),
					animationFactory_.getAnimationQueue());
			autoThread_ = new AutoSpawnThread(this);

			prefs.registerOnSharedPreferenceChangeListener(this);
			loadPrefs(prefs);

			display_.setRenderer(renderer_);
			addAnimation(200, 200);
		}

		private void loadPrefs(SharedPreferences prefs) {
			animationFactory_
					.setSpriteTexture(prefs.getInt("spriteChooser", 3));

			animationFactory_.setSpriteCount(prefs.getLong(
					"sprite_count_prefrence", 0xa0f05));

			autoThread_.setInterval(prefs.getInt(
					"raven_settings_auto_interval", 200));

			autoThreadPaused_ = prefs.getBoolean(
					"raven_settings_auto_checkbox_preference", false);

			touchEnabled_ = prefs.getBoolean(
					"raven_settings_general_touch_checkbox_preference", true);

			renderer_.setBackgroundColor(prefs.getLong("colorChooserSeekBar",
					0x0));

			animationFactory_.setSpriteScale(prefs.getLong(
					"sprite_size_prefrence", 0xa0f05));

			renderer_.setBackgroundImage(prefs.getString("IMAGE_PATH", null));

			renderer_.setBackgroundMode(prefs.getString(
					"background_options_spinner", ""));
		}

		@Override
		public void onCreate(SurfaceHolder surfaceHolder) {
			super.onCreate(surfaceHolder);
			setTouchEventsEnabled(true);
		}

		@Override
		public void onVisibilityChanged(boolean visible) {
			visible_ = visible;
			if (visible)
				onResume();
			else
				onPause();
		}

		@Override
		public void onSurfaceDestroyed(SurfaceHolder holder) {
			super.onSurfaceDestroyed(holder);
			visible_ = false;
		}

		public void onDestroy() {
			super.onDestroy();
			display_.requestExitAndWait();
			autoThread_.stop();
		}

		private void onPause() {
			autoThread_.pause();
			display_.onPause();
		}

		private void onResume() {

			display_.onResume();
			if (autoThreadPaused_) { // backwards >.<
				autoThread_.resume();
			}
		}

		@Override
		public void onSurfaceChanged(SurfaceHolder holder, int format,
				int width, int height) {
			animationFactory_.setDimentions(width, height);
			autoThread_.setDimentions(width, height);
			super.onSurfaceChanged(holder, format, width, height);
		}

		@Override
		public void onTouchEvent(MotionEvent event) {
			super.onTouchEvent(event);

			if (visible_ && touchEnabled_) {
				float x = 0;
				float y = 0;
				int action = event.getAction();
				switch (action & MotionEvent.ACTION_MASK) {
				case MotionEvent.ACTION_DOWN: {
					x = event.getX();
					y = event.getY();
					break;
				}

				case MotionEvent.ACTION_POINTER_DOWN: {
					final int pointerIndex = (action & MotionEvent.ACTION_POINTER_INDEX_MASK) >> MotionEvent.ACTION_POINTER_INDEX_SHIFT;
					final int pointerId = event.getPointerId(pointerIndex);
					x = event.getX(pointerId);
					y = event.getY(pointerId);
					break;
				}

				default: {
					return;
				}
				}

				addAnimation(x, y);
			}

		}

		public void addAnimation(float x, float y) {
			Animation a = animationFactory_.getAnimation(
					AnimationType.SPRITE_EXPLOSION, x, y);

			if (a == null) {
				return;
			}

			if (!renderer_.addAnimation(a)) {
				animationFactory_.recycle(a);
			} else {
				display_.requestRender();
			}
		}

		public void onSharedPreferenceChanged(SharedPreferences prefs,
				String key) {

			if (key.equalsIgnoreCase("sprite_count_prefrence")) {

				animationFactory_.setSpriteCount(prefs.getLong(key, 0));

			} else if (key.equalsIgnoreCase("spriteChooser")) {

				animationFactory_.setSpriteTexture(prefs.getInt(key, -1));

			} else if (key
					.equalsIgnoreCase("raven_settings_auto_checkbox_preference")) {

				autoThreadPaused_ = prefs.getBoolean(key, false);

			} else if (key.equalsIgnoreCase("raven_settings_auto_interval")) {

				autoThread_.setInterval(prefs.getInt(key, 5));

			} else if (key
					.equalsIgnoreCase("raven_settings_general_touch_checkbox_preference")) {

				touchEnabled_ = prefs.getBoolean(key, false);

			} else if (key.equalsIgnoreCase("colorChooserSeekBar")) {

				renderer_.setBackgroundColor(prefs.getLong(
						"colorChooserSeekBar", 0l));

			} else if (key.equalsIgnoreCase("sprite_size_prefrence")) {

				animationFactory_.setSpriteScale(prefs.getLong(key, 0));

			} else if (key.equalsIgnoreCase("IMAGE_PATH")) {

				renderer_.setBackgroundImage(prefs.getString(key, ""));
				renderer_.setBackgroundScale(prefs.getFloat("SCALE_X", 0),
						prefs.getFloat("SCALE_Y", 0));

			} else if (key.equalsIgnoreCase("background_options_spinner")) {

				renderer_.setBackgroundMode(prefs.getString(key, ""));
			}

		}

	}

}
